<?php
/**
 * Created by PhpStorm.
 * User: Eric-pc3
 * Date: 2018/8/2
 * Time: 18:37
 */

namespace app\common\service;

use app\common\logic\GoodsLogic;
use app\common\logic\MemberLogic;
use app\common\logic\OrderLogic;
use app\common\logic\SysLogic;
use think\facade\Log;

class OrderService extends BaseService
{
    /**
     * 获取订单分页
     * @param array $where 条件 当前 支持 status
     * @param int $pageIndex
     * @return array
     */
    public function getOrderPager($memberId,$where, $pageIndex = 1){
        // 内部条件
        $pWhere[] = ['o.member_id','=',$memberId];
        if(!empty($where['status'])){
            $pWhere[] = ['o.status','=',$where['status']];
        }
        $orderLogic = new OrderLogic();
        $pageSize = 50;
        if($pageIndex < 1){
            $pageIndex = 1;
        }
        $offset = (($pageIndex - 1) * $pageSize);
        $dataList = $orderLogic->_getOrderPager($pWhere,$offset,$pageSize,'o.create_time DESC');

        $orderEnum = config('site_enum.order');
        // 清除部分列
        $fanhuiData = [];
        foreach ($dataList as $r => $row) {
            $tmp = [];

            $tmp['id'] = $row['id'];
            $tmp['order_no'] = $row['order_no'];
            $tmp['payable'] = getOrderPayableByModel($row);
            $tmp['status'] = $row['status'];
            $tmp['status_text'] = $orderEnum['status'][$row['status']];

            // 处理商品 列
            $tmp['subs'] = serviceReturnDataListFieldFilter($row['subs'],[
                'goods_id',
                'goods_name',
                'goods_thumbs',
                'market_price',
                'total',
                'goods_option_id',
                'goods_option_title',
                'goods_option_thumb',
            ]);

            $fanhuiData[] = $tmp;
        }

        $fanhui = [
            'pagesize' => $pageSize,
            'total' => $orderLogic->_getOrderPagerCountByWhere($pWhere),
            'list' => $fanhuiData,
        ];

        return $this->retSuccess('成功', $fanhui);
    }
    /**
     * 提交订单
     * @param $memberId
     * @param $addressId
     * @param array $goodsArr
     * @param string $remark
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function submitOrder($memberId,$addressId,array $goodsArr,$remark = ''){
        if (empty($memberId)) {
            return $this->retError(1,'会员信息无效，请重新登陆');
        }
        if (!is_array($goodsArr)) {
            return $this->retError(1,'商品信息无效，请刷新页面重新提交');
        }
        // 查库 看地址是否存在
        $memberLogic = new MemberLogic();
        $addressWhere[] = ['id','=',$addressId];
        $addressWhere[] = ['member_id','=',$memberId];
        $addressModel = $memberLogic->_getAddressModelByWhere($addressWhere);
        if (empty($addressModel)) {
            return $this->retError(1,'地址信息无效，请刷新页面重新提交');
        }

        $cartIds = [];
        $totalMap = [];
        // 检测 goods_id  total 参数是否正确
        foreach ($goodsArr as &$item) {
            if(empty($item['goods_id'])){
                // 适配 goodsid  和 goods_id
                if(empty($item['goodsid'])){
                    return $this->retError(1,'商品序号出错');
                }
                else{
                    $item['goods_id'] = $item['goodsid'];
                }
            }

            // 检测 规格 ID   2018.09.26
            if(empty($item['option_id'])){
                return $this->retError(1,'商品规格出错');
            }

            if(empty($item['total'])){
                return $this->retError(1,'商品购买数量出错');
            }

            if(!isIntegerNumber($item['total'])){
                return $this->retError(1,'商品购买数量出错，请填写正整数');
            }

            $totalMap[  $item['goods_id'] . '_' . $item['option_id']  ] = $item['total'];

            // 记录 购物车 ids
            if(!empty($item['cartid'])){
                $cartIds[] = $item['cartid'];
            }
        }
        unset($item);

        $goodsLogic = new GoodsLogic();
        // 按 goods_id 和  option_id 取出 goodsList
        $goodsList = [];
        foreach ($goodsArr as $item) {
            $tmp = $goodsLogic->_getGoodsByIdAndOptionId($item['goods_id'],$item['option_id']);
            if(empty($tmp)){
                Log::error('商品规格不匹配 goods_id '.$item['goods_id'].' option_id ' . $item['option_id']);
                return $this->retError(1,'商品规格不匹配');
            }
            $goodsList[] = $tmp;
        }

        if(count($goodsArr) != count($goodsList)){
            return $this->retError(1,'提交商品数量和规格不一致');
        }
        foreach ($goodsList as $item) {
            if (empty($item['options'])) {
                Log::error('$goodsList 循环 时，options 不存在 $goods '.json_encode($item,256));
                return $this->retError(1,'商品规格不匹配');
            }
            if($totalMap[$item['id'] . '_' . $item['options']['id']] > $item['options']['stock']){
                return $this->retError(1,$item['goods_name'] . ' '. $item['options']['title'] . ' 最大允许购买 '. $item['options']['stock'] .' 件');
            }
        }

        $orderLogic = new OrderLogic();
        $jieguo = $orderLogic->saveOrder($memberId,$addressModel,$goodsList,$totalMap,$cartIds,$remark);
        if($jieguo['err_code'] != 0){
            return $this->retError(1,$jieguo['msg']);
        }

        return $this->retSuccess('成功', $jieguo['data']);
    }

    /**
     * 获取订单
     * @param $orderId
     * @return array
     */
    public function getOrder($memberId,$orderId){
        $orderLogic = new OrderLogic();
        $orderModel = $orderLogic->_getOrderModelById($orderId,$memberId);
        if (!empty($orderModel)) {
            // 处理 分转 元
            $orderModel['total_price'] = fenToYuan($orderModel['total_price']);
            $orderModel['original_total_price'] = fenToYuan($orderModel['original_total_price']);
            $orderModel['paid'] = fenToYuan($orderModel['paid']);
            $orderModel['dispatch_price'] = fenToYuan($orderModel['dispatch_price']);

            $subs = $orderModel['subs'];
            foreach ($subs as &$sub) {
                $sub['product_price'] = fenToYuan($sub['product_price']);
                $sub['market_price'] = fenToYuan($sub['market_price']);
                $sub['cost_price'] = fenToYuan($sub['cost_price']);
            }
            unset($sub);
            $goodsModel['options'] = $subs;
        }
        return $this->retSuccess('成功', $orderModel);
    }

    /**
     * 获取多个订单
     * @param $orderIds
     * @return array
     */
    public function getOrders($memberId,$orderIds){
        $orderLogic = new OrderLogic();
        $where[] = ['o.member_id','=',$memberId];
        $where[] = ['o.id','IN',$orderIds];
        $goodsList = $orderLogic->_getOrderPager($where);
        return $this->retSuccess('成功', $goodsList);
    }

    /**
     * 获取我的订单状态 数量 1 待付款 2 待发货 3 待收货
     * @param $memberId
     * @return array  1 待付款 2 待发货 3 待收货
     */
    public function getMyOrderStatusNum($memberId){
        // 1待付款 2待发货 3待收货
        $orderLogic = new OrderLogic();

        $fanhui['1'] = $orderLogic->_getOrderPagerCountByWhere([
            ['o.status','=',1],
            ['o.member_id','=',$memberId],
        ]);

        $fanhui['2'] = $orderLogic->_getOrderPagerCountByWhere([
            ['o.status','=',2],
            ['o.member_id','=',$memberId],
        ]);

        $fanhui['3'] = $orderLogic->_getOrderPagerCountByWhere([
            ['o.status','=',3],
            ['o.member_id','=',$memberId],
        ]);

        return $this->retSuccess('成功', $fanhui);
    }

    /**
     * 前端 订单变更
     * @param string $type 支持  del  cancel  finish
     * @param $memberId
     * @param $orderId
     * @return array
     */
    private function orderChange($type,$memberId,$orderId,$other = []){
        $allowType = [
            'del',
            'cancel',
            'finish',
        ];

        $typeText = '';
        $postData = array_merge($other);

        switch ($type){
            case 'del':
                $typeText = '删除';
                // 软删除
                $postData['delete_time'] = time();
                break;
            case 'finish':
                // 完成订单
                $postData['status_step'] = +1;
                $typeText = '完成';
                break;
            case 'cancel':
                // 取消订单
                $postData['status_step'] = -1;
                $typeText = '取消';
                break;
            default:
                break;
        }

        if (!in_array($type, $allowType)) {
            Log::error(' OrderService > orderChange 输入的类型不支持 $allowType ' . json_encode($allowType,256).' $type ' . $type);
            return $this->retError(1, $typeText . '失败，请联系管理员！');
        }

        $orderLogic = new OrderLogic();

        $jieguo = $orderLogic->changeOrder($orderId,0,$memberId,$postData);

        if($jieguo['err_code'] != 0){
            Log::error(' OrderService > orderChange changeOrder 失败消息 ‘'.$jieguo['msg']
                .'’ $allowType ' . json_encode($allowType,256).' $type ' . $type . ' $postData '.json_encode($postData,256));

            return $this->retError(1, $typeText .'失败');
        }
        else{
            return $this->retSuccess($typeText .'成功');
        }
    }

    public function delOrder($memberId,$orderId){
        return $this->orderChange('del', $memberId, $orderId);
    }

    public function cancelOrder($memberId,$orderId,$remark = ''){
        $other = [];
        if(!empty($remark)){
            $other['remark'] = $remark;
        }
        return $this->orderChange('cancel', $memberId, $orderId,$other);
    }

    public function finishOrder($memberId,$orderId){
        return $this->orderChange('finish', $memberId, $orderId);
    }

    /**
     * 按订单号 查物流
     * @param $memberId
     * @param $orderId
     * @return array
     */
    public function expressByOrderId($memberId,$orderId){
        $orderLogic = new OrderLogic();
        $orderModel = $orderLogic->_getOrderModelById($orderId);
        if (empty($orderModel)) {
            return $this->retError(1,'订单 不存在');
        }
        if($orderModel['member_id'] != $memberId){
            return $this->retError(1,'无法操作别人的订单');
        }

        return $this->expressByOrderModel($orderModel);
    }

    /**
     * 按物流信息 查物流
     * @param $expressSn
     * @param $express
     * @return array
     */
    public function expressByExpressSn($expressSn,$express){
        $sysLogic = new SysLogic();
        $jieguo = $sysLogic->showExpress($expressSn,$express);
        if($jieguo['err_code'] != 0){
            return $this->retError(1,'物流查询失败');
        }
        else{
            return $this->retSuccess('物流查询成功',$jieguo['data']);
        }
    }

    /**
     * 按 orderModel 查物流
     * @param $orderModel
     * @return array
     */
    public function expressByOrderModel($orderModel){
        return $this->expressByExpressSn($orderModel['oe_express_sn'], $orderModel['oe_express']);
    }
}